package com.young.zuul.filter;

import com.alibaba.fastjson2.JSONObject;
import com.young.common.model.ResultEnum;
import com.young.common.utils.JJwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private static final String[] IGNORE_URL_ARRAY;

    static {
        IGNORE_URL_ARRAY = new String[]{
                "/swagger/", "/static/", "/file/", "/wx/", "/template/",
                "subscriber/",
                "/api-docs", "user/subscribe", "user/unsubscribe", "user/login"
        };
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String accessUri = exchange.getRequest().getURI().toString();
        log.info("Access uri is [{}]", accessUri);
        if (Arrays.stream(IGNORE_URL_ARRAY).anyMatch(accessUri::contains)) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("Authorization");
        if (null == token || token.length() == 0) {
            return response.writeWith(Mono.just(returnResult(response, ResultEnum.E_401.getCode(), "Token is required!")));
        } else {
            try {
                Claims claims = JJwtUtils.parseToken(token);
                String subject = claims.getSubject();
                ServerHttpRequest.Builder mutate = request.mutate();
                mutate.header("authUserId", subject);
                ServerHttpRequest buildRequest = mutate.build();
                log.info("Cloud gateway redirect success!");
                return chain.filter(exchange.mutate().request(buildRequest).build());
            } catch (ExpiredJwtException e) {
                log.error("Token超时！", e);
                return response.writeWith(Mono.just(returnResult(response, ResultEnum.E_401.getCode(), "Token is expired!")));
            } catch (Exception e) {
                log.error("Token异常！", e);
                return response.writeWith(Mono.just(returnResult(response, ResultEnum.E_401.getCode(), "Resource is forbidden!")));
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 2;
    }

    private DataBuffer returnResult(@NotNull ServerHttpResponse response, @NotNull Integer code, String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        if (null != message) jsonObject.put("message", message);
        byte[] bits = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.resolve(code));
        response.getHeaders().add("Content-Type","text/plain;charset=utf-8");
        return buffer;
    }

}
